package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.hmdp.common.RedisIdWorker;
import com.hmdp.common.lock.Impl.SimpleRedisLock;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.SeckillVoucherMapper;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 * 秒杀优惠券表，与优惠券是一对一关系 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2022-01-04
 */
@Service
@Slf4j
public class SeckillVoucherServiceWithLock {

    @Autowired
    private RedisIdWorker idWorker;

    @Resource
    private SeckillVoucherMapper seckillVoucherMapper;

    @Autowired
    private IVoucherOrderService voucherOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public Result seckillVoucher(Long voucherId) {
        SeckillVoucher voucher = seckillVoucherMapper.queryById(voucherId);
        if(Objects.isNull(voucher)){
            Result.fail("改秒杀券不存在");
        }
        //判断秒杀是否开始
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            Result.fail("秒杀尚未开始！");
        }
        //秒杀是否结束
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            Result.fail("秒杀已经结束！");
        }
        //库存是否充足
        if(voucher.getStock()<1){
            Result.fail("库存不足！");
        }
        Long userId = UserHolder.getUser().getId();

        SimpleRedisLock lock = new SimpleRedisLock(redisTemplate,"order:"+userId);
        Boolean tryLock = lock.tryLock(30L);
        if(BooleanUtil.isFalse(tryLock)){
            //没有获取锁
            Result.fail("不可重复购买");
        }
        try {
            SeckillVoucherServiceWithLock currentProxy = (SeckillVoucherServiceWithLock) AopContext.currentProxy();
            return currentProxy.createVoucherOrder(voucherId,userId);
        }finally {
            lock.unLock();
        }
    }

    @Transactional
    public Result createVoucherOrder(Long voucherId,Long userId){
        Integer count = seckillVoucherMapper.countByUserIdAndVoucherId(voucherId, userId);
        if(count>0){
            return Result.fail("不可重复下单");
        }
        //扣减库存
        boolean success = seckillVoucherMapper.minusStcokOne(voucherId);
        if(!success){
            return Result.fail("库存不足！");
        }
        //创建订单
        VoucherOrder order = new VoucherOrder();
        order.setVoucherId(voucherId)
                .setId(idWorker.nextId("order"))
                .setUserId(userId);
        voucherOrderService.save(order);
        return Result.ok(order.getId());
    }
}
